import rooms.room as room
import random


class Wzq(room.Room):
    boardSize = 15

    def __init__(self, server, roomid):
        super().__init__(2, server, roomid)

    async def start(self):
        self.next = random.randint(0, self.maximum - 1)
        self.board = [[-1 for i in range(self.boardSize)] for j in range(self.boardSize)]
        await self.sendall({"command": "start", "data": {"board": self.board, "next": self.next}}, withid=True)

    @room.add
    async def act(self, pid, data):
        if self.next != pid:
            return
        x, y = data['data']
        if self.board[x][y] != -1:
            return
        self.board[x][y] = pid
        self.next += 1
        self.next %= self.maximum
        await self.sendall({"command": "act", "pid": pid, "data": [x, y], "next": self.next})
        arr = [[-1, -1], [-1, 0], [-1, 1], [0, -1]]
        for a in arr:
            n = 0
            for flag in [1, -1]:
                for i in range(1, 5):
                    xx = x + a[0] * i * flag
                    yy = y + a[1] * i * flag
                    if (0 <= xx < self.boardSize and
                            0 <= yy < self.boardSize and
                            self.board[xx][yy] == pid):
                        n += 1
                    else:
                        break
            if n >= 4:
                await self.win(pid)
                break
                # await self.sendall({"command": "win", "pid": pid})
                # self.board = [[-1 for i in range(self.boardSize)] for j in range(self.boardSize)]
                # break
